package com.kun.admin.controller;


import com.kun.base.model.User;
import com.kun.base.shiro.service.SSOService;
import com.kun.base.web.model.AjaxResult;
import com.kun.util.MD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by likun on 2016/8/24 0024.
 */
@Controller
@RequestMapping("/admin")
public class UserLoginController {

    @Autowired
    private SSOService ssoService;

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(User user, boolean remember, HttpSession session){
        String message;
        if (StringUtils.isEmpty(user.getUsername()) || user.getPassword() == null) {
            message= "用户名或密码不能为空";
            return new AjaxResult(false,message);
        }

        String password= MD5.GetMD5Code(user.getPassword());
        user.setPassword(password);

        //1. 接受提交的当事人和证书：
        AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), password, remember);

        //2. 获取当前Subject：
        Subject currentUser = SecurityUtils.getSubject();

        //3. 登录：
        try {
            // 登录验证
            currentUser.login(token);

            ssoService.addUserToOnline(session);

            return new AjaxResult(true,"登录成功");
        } catch (UnknownAccountException uae) {
            message = "用户名或密码不正确";
        } catch (IncorrectCredentialsException ice) {
            message = "用户名或密码不正确";
        } catch (LockedAccountException lae) {
            message = "该账号已被冻结";
        } catch (ExcessiveAttemptsException eae) {
            message = "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            message = "用户名或密码不正确";
        }
        return new AjaxResult(false,message);
    }
}
